package com.videoweb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors().configurationSource(corsConfigurationSource())
            .and()
            .csrf().disable()
            .authorizeRequests()
                // 公开的GET API端点
                .antMatchers(HttpMethod.GET,
                    "/api/videos/**",             // 所有视频相关GET请求
                    "/api/comments/video/**",      // 视频评论GET请求
                    "/api/danmaku/video/**"       // 视频弹幕GET请求
                ).permitAll()
                // 公开的静态资源
                .antMatchers(
                    "/",
                    "/index.html",
                    "/login.html",
                    "/register.html",
                    "/player.html",
                    "/css/**",
                    "/js/**",
                    "/images/**",
                    "/fonts/**",
                    "/uploads/**",
                    "/favicon.ico",
                    "/error"
                ).permitAll()
                // 公开的认证API端点
                .antMatchers("/api/auth/login", "/api/auth/register", "/api/auth/user").permitAll()
                // 公开的弹幕API端点 - 允许匿名用户发送弹幕
                .antMatchers(HttpMethod.POST, "/api/danmaku/**").permitAll()
                // 需要认证的API端点
                .antMatchers(HttpMethod.POST, 
                    "/api/comments/**",           // 评论需要登录
                    "/api/videos/**"              // 视频上传需要登录
                ).authenticated()
                .antMatchers("/api/auth/logout").authenticated()
                // 受保护的页面
                .antMatchers(
                    "/upload.html",
                    "/profile.html"
                ).authenticated()
                // 其他所有请求允许访问（包括首页等公开资源）
                .anyRequest().permitAll()
            .and()
                .formLogin().disable() // 禁用默认登录表单
                .httpBasic().disable() // 禁用HTTP Basic认证
                .exceptionHandling()
                .authenticationEntryPoint((request, response, e) -> {
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    if (request.getRequestURI().startsWith("/api/")) {
                        response.setStatus(401);
                        response.getWriter().write("{\"error\":\"Unauthorized\",\"message\":\"请登录后访问此资源\"}");
                    } else {
                        response.sendRedirect("/login.html?redirect=" + java.net.URLEncoder.encode(request.getRequestURI(), "UTF-8"));
                    }
                });

        return http.build();
    }
}
